<template>
  <div class="xtx-pagination">
    <a href="javascript:;" v-if="currentpage > 1" @click="currentpage--">
      上一页
    </a>
    <a href="javascript:;" v-else class="disabled">上一页</a>
    <span v-if="currentarr[0] > 1">...</span>
    <a
      href="javascript:;"
      @click="currentpage = i"
      :class="{ active: i === currentpage }"
      v-for="i in currentarr"
      :key="i"
    >
      {{ i }}
    </a>
    <span v-if="currentpage < Math.ceil(total / pagesize)">...</span>
    <a
      href="javascript:;"
      v-if="currentpage < Math.ceil(total / pagesize)"
      @click="currentpage++"
    >
      下一页
    </a>
    <a href="javascript:;" v-else>下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    total: {
      type: Number,
      default: 100
    },
    pagesize: {
      type: Number,
      default: 5
    },
    currentPage: {
      type: Number,
      default: 1
    }
  },
  setup (props, { emit }) {
    // 页面展示多少页码
    const count = 5
    // 当前页码
    const currentpage = ref(1)
    watch(
      () => props.currentPage,
      (newva) => {
        currentpage.value = newva
      },
      { immediate: true }
    )
    // 页面中页码数组
    const currentarr = computed(() => {
      const offset = Math.floor(count / 2)
      let start = currentpage.value - offset
      let end = start + count - 1
      const num = Math.ceil(props.total / props.pagesize)
      if (start < 1) {
        start = 1
        end = start + count - 1 > num ? num : start + count - 1
      }
      if (end > num) {
        end = num
        start = end - offset + 1 > 0 ? end - count + 1 : 1
      }
      const arr = []
      for (let i = start; i <= end; i++) {
        arr.push(i)
      }
      return arr
    })
    // 页码改变，通知父组件
    watch(currentpage, (newvalue) => {
      emit('currentchange', newvalue)
    })
    return { currentarr, currentpage }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333;
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
